﻿
using EmperialApps.WeatherSpark.Data;
using EmperialApps.WeatherSpark.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System;
using System.Windows;
using System.Windows.Controls;

namespace EmperialApps.WeatherSpark.Internal {

    /// <summary>Manages trial mode features.</summary>
    internal sealed class TrialManager {

        private readonly PhoneApplicationPage _page;
        private readonly IApplicationBar _appBar;
        private ApplicationBarMenuItem _purchaseMenuItem;

        /// <summary>Gets or sets the container for the ad display.</summary>
        public Panel AdContainer { get; set; }


        /// <summary>Initializes a new instance of the <see cref="TrialManager"/> class for the specified page.</summary>
        public TrialManager( PhoneApplicationPage page ) {
            this._page = page;

            this._appBar = page.ApplicationBar;
        }


        /// <summary>Enables or disables trial mode features, based on the value of <see cref="App.IsTrial"/>.</summary>
        public void Update( ) {
            if( App.IsTrial )
                this.EnterTrialMode( );
            else
                this.ExitTrialMode( );
        }

        /// <summary>Removes trial mode features when leaving a page.</summary>
        public void Clear( ) {
            this.ExitTrialMode( );
        }


        #region Private Members

        private void EnterTrialMode( ) {
            if( this._purchaseMenuItem != null )
                return;

            this._page.GetType( ).Log( "Entering trial mode" );
            if( this.AdContainer != null ) {
                this.AdContainer.Children.Add( new AdDuplex.AdControl {
#if DEBUG
                    IsTest = true,
#endif
                    AdUnitId = "17631"
                } );
                this.AdContainer.Visibility = Visibility.Visible;
            }

            this._purchaseMenuItem = this._appBar.AddMenuItem( Localized.Menu.purchase, this.OnPurchaseClicked );
        }

        private void ExitTrialMode( ) {
            if( this._purchaseMenuItem == null )
                return;

            this._page.GetType( ).Log( "Exiting trial mode" );
            this._appBar.MenuItems.Remove( this._purchaseMenuItem );
            this._purchaseMenuItem = null;

            if( this.AdContainer != null ) {
                this.AdContainer.Visibility = Visibility.Collapsed;
                this.AdContainer.Children.Clear( );
            }
        }

        private void OnPurchaseClicked( object sender, EventArgs e ) {
            this._page.GetType( ).Log( "Purchase menu clicked" );
            var marketplaceTask = new MarketplaceDetailTask( );
            marketplaceTask.Show( );
#if DEBUG
            App.IsTrial = false;
#endif
        }

        #endregion

    }

}
